# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db import connection, transaction

from buildbotweb.buildbot.models import Tests, TestRuns, UnitTestResults, TestSuites, TestSuiteRuns, TestResults

def testrunsindex(request, testsuite_id=None):
    if testsuite_id:
        testrun_list = TestRuns.objects.all().filter(testsuiterun__testsuite__id = testsuite_id).order_by('testtime').reverse()
        testsuite = TestSuites.objects.get(id=testsuite_id).testsuite
    else:
        testrun_list = TestRuns.objects.all().order_by('testtime').reverse()
        testsuite = 'All'
    #testrun_list = TestRuns.objects.all().order_by('testtime')

    testruns = paginate(request, testrun_list)
    return render_to_response('testruns/index.html', {'testruns': testruns, 'testsuite':testsuite})

def testrunsdetail(request, testrun_id):
    #r = get_object_or_404(TestRuns, pk=testrun_id)
    testrun = TestRuns.objects.get(id=testrun_id)
    test = testrun.test
    results = [{'results':'N/A'}]
    if testrun.test.testtype_id == 2:
        vals = testrun.unittestresults_set.all().values()
        if vals:
            results = vals
    elif testrun.test.testtype_id == 1:
        vals = testrun.mailtestresults_set.all().values()
        if vals:
            results = vals
    else:
        results = testrun.testresults_set.all().values('result_name','result_value')
        #if vals:
        #    results = {}
        #    for val in vals:
        #        results[val.result_name] = val.result_value
        #    results = [results]
        #if vals:
        #    results = [dict(map(lambda x: map(lambda y: x.get(y), x.keys()), vals)).items()]

    #tests = Tests.objects.filter(testsuitetests__testsuite = tsr.testsuite.id)
    #test = Tests.obje
    return render_to_response('testruns/details.html', {'testrun': testrun, 'test':test, 'results':results})

def resultsindex(request):
    testsuite_list = TestSuites.objects.all().order_by('id')
    return render_to_response('results/index.html', {'testsuites': testsuite_list})

def results(request, suiteid = None):
    results = UnitTestResults.objects.all().order_by('testrun')
    cursor = connection.cursor()

    sqlstr = """
        SELECT DISTINCT
            a.id,
            svnrev, 
            numtests as alltests,
            numtests - numerrors as runnabletests,
            numtests - numerrors - numfailures as passingtests,
            statements,
            statements_executed,
            (statements_executed * 1.0 / statements * 1.0) * 100.0  as pct_coverage
        FROM buildbot_unittestresults a 
        INNER JOIN buildbot_testruns b 
        INNER JOIN buildbot_testsuiteruns c
        ON 
            a.testrun_id = b.id 
            AND b.testsuiterun_id = c.id
    """
    if suiteid:
        sqlstr = "%s\n%s" % (
            sqlstr,
            "WHERE c.testsuite_id = %s" % suiteid
        )

    cursor.execute(sqlstr)
    utest_rows = cursor.fetchall()
    counter = range(len(utest_rows))


    return render_to_response('results/resultgraph.html', {'counter': counter, 'results': results, 'utest_results': utest_rows})

def allresults(request):
    return results(request, None)

def testsuiteindex(request):
    test_suites_all = TestSuites.objects.all().order_by('id').reverse()

    test_suites = paginate(request, test_suites_all)
    return render_to_response('testsuites/index.html', {'testsuites': test_suites})

def testsuitedetails(request, testsuite_id):
    testsuite = TestSuites.objects.all().filter(id=testsuite_id)[0]
    tests = Tests.objects.filter(testsuitetests__testsuite = testsuite.id)
    return render_to_response(
            'testsuites/detail.html', 
            {'testsuite': testsuite, 'tests': tests}
    )

# Nice example of using default detail view
def __testsuitedetails(request, testsuite_id):
    testsuite = TestSuites.objects.all().filter(id=testsuite_id)
    return render_to_response('detail.html', {'data': testsuite.values(), 'title':'Test Suite Detail'})

def testresultsindex(request):
    test_results_all = TestResults.objects.all().order_by('id').reverse().values()
    return genericindex(request, test_results_all, 'Test Results Index')

    testresults = paginate(request, test_results_all)
    return render_to_response('testresults/index.html', {'testresults': testresults})

def testsindex(request):
    tests = Tests.objects.all().values()
    return genericindex(request, tests, 'Tests Index') 

def paginate(request, data_all):
    paginator = Paginator(data_all, 25)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        data = paginator.page(page)
    except (EmptyPage, InvalidPage):
        data = paginator.page(paginator.num_pages)

    return data

def genericindex(request, data_all, title=''):
    data = paginate(request, data_all)
    return render_to_response('index.html', {'data': data, 'title':title})

def testresults(request, testid = None, testsuiteid = None):
    test = Tests.objects.get(id = testid)
    if testid and testsuiteid:
        testruns = TestRuns.objects.filter(test__id=testid, testsuiterun__testsuite__id=testsuiteid)
    elif testid:
        testruns = TestRuns.objects.filter(test__id=testid)
    elif testsuiteid:
        testruns = TestRuns.objects.filter(testsuiterun__testsuite__id=testsuiteif)
    else:
        return testresultsindex(request)

    keys = []
    results = []
    count = 0
    for testrun in testruns:
        data = testrun.testresults_set.values('result_name', 'result_value')
        #data.sort()

        if data:
            result = {}
            result['svnrev'] = testrun.testsuiterun.svnrev
            result['data'] = data
            result['count'] = count
            if not keys:
                keycount = 2
                for datum in data:
                    t_result = datum.get('result_name')
                    # For some reason string.translate will not work.  Odd.
                    t_result = t_result.replace(".", "_")
                    t_result = t_result.replace("_", "_")
                    t_result = t_result.replace("/", "_")
                    t_result = t_result.replace("-", "_")
                    keys.append({'name':t_result,'id':keycount})
                    keycount+=1
            results.append(result)
            count += 1

        #testrun_ids = testrun.testresults_set.values('testrun').distinct()

        #for testrun_id in testrun_ids:
        #    id = testrun_id.get('testrun')
        #    data = TestResults.objects.filter(testrun=id)
        #    trets = []
        #    for datum in data:
        #        trets.append((datum.result_name, datum.result_value))
        #    trets.sort()
        #    results.append(trets)

    return render_to_response('testresults/testresults.html', {'results':results, 'keys':keys, 'test':test})

def main(request, site_url=""):
    try:
        tsr = TestSuiteRuns.objects.latest('testtime')
    # Probably should check for DoesNotExist error explicitly
    except:
        tsr = {}
    return render_to_response('main/index.html', {'tsr':tsr,'site_url':site_url})

def running_testsuites(request):
    testrun_list = TestSuiteRuns.objects.all().order_by('testtime').reverse()
    #testrun_list = TestRuns.objects.all().order_by('testtime')

    testsuiteruns = paginate(request, testrun_list)
    return render_to_response('testsuiteruns/index.html', {'testsuiteruns': testsuiteruns})

def testsuiterun_details(request, tsr_id):
    tsr = TestSuiteRuns.objects.get(id=tsr_id)
    
    tests = Tests.objects.filter(testsuitetests__testsuite = tsr.testsuite.id)
    testsuite = TestSuites.objects.get(id=tsr.testsuite.id)
    testruns = TestRuns.objects.filter(testsuiterun = tsr)

    surf = {
        'next':tsr.id + 1,
        'prev':tsr.id - 1
    }

    return render_to_response(
        'testsuiteruns/details.html', 
        {'tests': tests, 'testsuite': testsuite, 'tsr':tsr, 'testruns':testruns, 'surf':surf}
    )

